package com.hp.bon.sgw.core.processor;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.InprogressMessageQueue;
import com.hp.bon.sgw.core.channel.IChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.core.route.RouteInfo;
import com.hp.bon.sgw.domain.Node;
import org.slf4j.Logger;

public class ForwardProcessor extends Processor
{
  public int process(CallParam callParam)
  {
    RouteInfo r = ChannelServer.findRoute(callParam.getServiceContextId());
    int ret = 0;
    if (r == null) {
      callParam.setResultMsg("no Route for " + callParam.getServiceContextId());
      ret = 3002;
    } else if (r.result != 0) {
      callParam.setResultMsg("Route unavailable for " + callParam.getServiceContextId());
      ret = r.result;
    }
    if (ret != 0) {
      callParam.setRetCode(ret);
      endProcess(callParam);
      return 0;
    }

    callParam.setToNode(r.curNode);
    Constants.LOG.info("ForwardProcessor messsage to " + r.curNode.getHostId() + ",sessionId:" + callParam.getSessionId());
    InprogressMessageQueue.getInstance().addRequest(callParam);
    r.curNode.getChannel().sendRequest(callParam);
    return 0;
  }

  public int endProcess(CallParam callParam)
  {
    if (Constants.LOG.isDebugEnabled()) {
      Constants.LOG.debug("ForwardProcessor handleAnswer");
    }
    callParam.getAsynHandler().onCallResult(callParam);
    return 0;
  }
}